/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yheriatovych.reductor.example.slice;

import com.yheriatovych.reductor.Actions;
import com.yheriatovych.reductor.Cancelable;
import com.yheriatovych.reductor.Cursors;
import com.yheriatovych.reductor.Store;
import com.yheriatovych.reductor.example.MainAbility;
import com.yheriatovych.reductor.example.ResourceTable;
import com.yheriatovych.reductor.example.SampleItemProvider;
import com.yheriatovych.reductor.example.dialog.SelectedDialog;
import com.yheriatovych.reductor.example.dialog.SelectedListener;
import com.yheriatovych.reductor.example.model.AppState;
import com.yheriatovych.reductor.example.model.NotesFilter;
import com.yheriatovych.reductor.example.reductor.filter.FilterActions;
import com.yheriatovych.reductor.example.reductor.notelist.NotesActions;
import com.yheriatovych.reductor.example.reductor.utils.UndoableReducer;
import com.yheriatovych.reductor.example.util.NumCalcUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * demo
 *
 * @since 2021-05-06
 */
public class MainAbilitySlice extends AbilitySlice implements SelectedListener {
    private NotesActions notesActions;
    private ListContainer listContainer;
    private Store<AppState> store;
    private SampleItemProvider sampleItemProvider;
    private AtomicInteger idGenerator = new AtomicInteger();
    private Cancelable mCancelable;
    private ShapeElement selected;
    private ShapeElement unselected;
    private final int mSelectedColor = 0xFFAAffff;
    private final int mUnSelectedColor = 0xFFCCCCCC;
    private final int mTextFieldBottomColor = 0xFFFF4081;
    private final int mButtonColor = 0xFFBFBFBF;
    private final int num2 = 2;
    private final int num15 = 15;
    private Text mSelectedText;
    private String[]mText = {"ALL","CHECKED","UNCHECKED"};

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        store = ((MainAbility) getAbility()).getStore();
        notesActions = Actions.from(NotesActions.class);

        selected = new ShapeElement();

        selected.setRgbColor(RgbColor.fromArgbInt(mSelectedColor));

        unselected = new ShapeElement();

        unselected.setRgbColor(RgbColor.fromArgbInt(mUnSelectedColor));

        initSelectedButton();
        initOperatorButton();
        initUndoButton();
        initListContainer();
    }

    private void initSelectedButton() {
        mSelectedText = (Text) findComponentById(ResourceTable.Id_selected_text);
        Component component = findComponentById(ResourceTable.Id_select);
        component.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Point point = new Point();
                DisplayManager.getInstance().getDefaultDisplay(MainAbilitySlice.this).get().getRealSize(point);
                float offsetY = NumCalcUtil.subtract(NumCalcUtil.divide(point.getPointY(), num2),
                        component.getLocationOnScreen()[1]);
                new SelectedDialog(MainAbilitySlice.this, MainAbilitySlice.this::selected, offsetY).show();
            }
        });
    }

    private void initUndoButton() {
        Image undo = (Image) findComponentById(ResourceTable.Id_undo_btn);
        undo.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                store.dispatch(UndoableReducer.pop());
                sampleItemProvider.notifyDataChanged();
            }
        });

        undo.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                Component rootLayout = LayoutScatter
                        .getInstance(getContext()).parse(ResourceTable.Layout_toast_layout, null, true);
                Component bg = rootLayout.findComponentById(ResourceTable.Id_toast_bg);
                ShapeElement shapeElement = new ShapeElement();
                shapeElement.setCornerRadius(num15);
                shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.GRAY.getValue()));
                bg.setBackground(shapeElement);
                ToastDialog toast = new ToastDialog(getContext());
                toast.setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT,
                        ComponentContainer.LayoutConfig.MATCH_CONTENT);
                toast.setCornerRadius(AttrHelper.fp2px(num15, getContext()));
                int offsetY = (int) NumCalcUtil.divide(getDisplay().height, num2);
                toast.setOffset(0, offsetY);
                toast.setTransparent(true);
                toast.setComponent(rootLayout).show();
            }
        });
    }

    private void initOperatorButton() {
        TextField textField = (TextField) findComponentById(ResourceTable.Id_text);
        textField.addDrawTask(new Component.DrawTask() {
            @Override
            public void onDraw(Component component, Canvas canvas) {
                Paint paint = new Paint();
                paint.setColor(new Color(mTextFieldBottomColor));
                int height = AttrHelper.fp2px(num2, MainAbilitySlice.this);
                canvas.drawRect(0,component.getHeight() - height,component.getWidth(),component.getHeight(), paint);
            }
        });

        Button btn = (Button) findComponentById(ResourceTable.Id_add_btn);

        ShapeElement shapeElement = new ShapeElement();

        shapeElement.setCornerRadius(num15);
        shapeElement.setRgbColor(RgbColor.fromArgbInt(mButtonColor));
        btn.setBackground(shapeElement);

        btn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                int id = idGenerator.getAndIncrement();
                store.dispatch(notesActions.add(id, textField.getText() == null
                        || textField.getText().trim().length() == 0 ? " " : textField.getText()));
                textField.setText(null);
                sampleItemProvider.notifyDataChanged();
                sampleItemProvider.notifyDataInvalidated();
            }
        });
    }

    private DisplayAttributes getDisplay() {
        DisplayAttributes displayAttributes = null;
        Optional<Display> optionalDisplay = DisplayManager.getInstance().getDefaultDisplay(getContext());
        if (optionalDisplay.isPresent()) {
            displayAttributes = optionalDisplay.get().getAttributes();
        }
        return displayAttributes;
    }

    private void changeSelectedText(int index) {
        mSelectedText.setText(mText[index]);
    }

    private void initListContainer() {
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        listContainer.setLongClickable(false);
        sampleItemProvider = new SampleItemProvider(store.getState().notes(), this,
                note -> store.dispatch(notesActions.toggle(note.getId())),
                note -> store.dispatch(notesActions.remove(note.getId())));
        mCancelable = Cursors.forEach(store, state -> {
            sampleItemProvider.setNotes(state.getFilteredNotes());
            changeSelectedText(state.filter().ordinal());
            sampleItemProvider.notifyDataChanged();
        });
        listContainer.setItemProvider(sampleItemProvider);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void selected(int index) {
        NotesFilter filter = NotesFilter.values()[index];
        store.dispatch(Actions.from(FilterActions.class).setFilter(filter));
        sampleItemProvider.notifyDataChanged();
        changeSelectedText(index);
    }
}